package com.ssd.interceptor;


import com.ssd.exception.LogicException;
import com.ssd.utils.*;
import com.dkd.common.core.domain.model.LoginUser;
import com.ssd.view.TokenObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author itcast
 */
@Slf4j
@Component
public class UserContextInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.尝试获取头信息中的用户信息
        String token = getToken(request);
        //2.令牌非空判断
        if (!StringUtils.isNotEmpty(token)) {
            TokenObject tokenObject=new TokenObject();
            tokenObject.setUserId(1L);
            tokenObject.setLoginType(1L);
            tokenObject.setUserName("小黎");
            tokenObject.setMobile("110");
            UserContext.set(tokenObject);



            return true;
//            log.info("请求token，不存在！");
//            throw new LogicException("请先登录！");
        }
        //2.解析令牌数据并获取到uui，再组成从缓存中获取用户信息的key
        Claims claims = Jwts.parser().setSigningKey("abcdefghijklmnopqrstuvwxyz").parseClaimsJws(token).getBody();
        String uuid = (String) claims.get("login_user_key");
        String userKey = "login_tokens:" + uuid;
        LoginUser user = (LoginUser)redisTemplate.opsForValue().get(userKey);
        if (user != null){
            TokenObject tokenObject=new TokenObject();
            tokenObject.setUserId(user.getUserId());
            tokenObject.setLoginType(user.getUser().getRoles().get(0).getRoleId());
            tokenObject.setUserName(user.getUser().getNickName());
            tokenObject.setMobile(user.getUser().getPhonenumber());
            UserContext.set(tokenObject);
            //5.再把token也放到threadLocal中，已便远程调用
            TokenContext.set(token);
            return true;
        }
        throw new LogicException("请先登录！");
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer ")) {
            token = token.replace("Bearer ", "");
        }
        return token;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户信息
        UserContext.clear();
        //清理token数据
        TokenContext.clear();
    }
}
